package com.dingli.db;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DatabaseUtil {

    public static Connection getConnection() throws SQLException {
        try {
            // 创建初始上下文
            Context initContext = new InitialContext();
            // 从 JNDI 获取资源
            DataSource dataSource = (DataSource) initContext.lookup("java:/comp/env/jdbc/MyDB");
            // 从连接池获取连接
            return dataSource.getConnection();
        } catch (Exception e) {
            throw new SQLException("Error obtaining database connection", e);
        }
    }
}

